/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import Merlion.util.state.SalesDocumentState;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import managedBean.SalesInquiryManagedBean;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperRunManager;

/**
 *
 * @author Toshiba
 */
@WebServlet(name = "salesInquiryServlet", urlPatterns = {"/salesInquiryServlet", "/salesInquiryServlet?*"})
public class salesInquiryServlet extends HttpServlet {

    @Resource(name = "jasperjdbc")
    private DataSource jasperjdbc;
    private Long selectedPrintInquiryID;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException, JRException {
        //   response.setContentType("text/html;charset=UTF-8");
        //    PrintWriter out = response.getWriter();
        System.out.println("PROCESS REQUEST IN SERVLET");
        try {
            
            // Long salesInquiryId = Long.parseLong(request.getParameter("salesInquiryId"));
            //  Long salesInquiryId = smb.getSelectedViewInquiry().getId();
            //  Map requestMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
            //  Long salesInquiryId = Long.parseLong(requestMap.get("salesInquiryId").toString());
            
            selectedPrintInquiryID = (Long)request.getSession(true).getAttribute("selectedPrintInquiryID");
            
           // request.getSession().setAttribute("salesInquiryId", smb.getSelectedPrintInquiryID());
            //String sI = request.getSession().getAttribute("salesInquiryId").toString();
            String sI = String.valueOf(selectedPrintInquiryID) ;
            System.out.print("salesOrderId: " + sI);
            String strSQL = "SELECT CT.ADDRESS, CT.ADDRESSSTATE, CT.CITY, CT.COUNTRY, CT.POSTALCODE, SD.DOCUMENTNAME, SI.ID, SD.DATEISSUED,"
                    + " C.NAME, CT.LASTNAME, CT.FIRSTNAME, CT.CONTACTNUM, L.ITEMID, L.ITEMNAME, L.PRICE, L.QUANTITY, L.TOTALLINEPRICE"
                    + " FROM SALESINQUIRYENTITY SI"
                    + " INNER JOIN SALESDOCUMENTENTITY SD ON SI.ID = SD.ID"
                    + " INNER JOIN CLIENTENTITY C ON C.ID = SD.CLIENT_ID"
                    + " INNER JOIN CONTACTENTITY CT ON CT.ID = SD.CONTACT_ID"
                    + " INNER JOIN SALESDOCUMENTENTITY_LINEENTRYENTITY SL ON SD.ID = SL.SALESDOCUMENTENTITY_ID"
                    + " INNER JOIN LINEENTRYENTITY L ON SL.LINEENTRYLIST_ID = L.ID"
                    + " WHERE SI.ID = " + sI;
            System.out.print("strSQL: " + strSQL);
            //   + salesInquiryId.toString();
            //  + request.getSession().getAttribute("salesInquiryId").toString();

            //   SalesInquiryManagedBean smb = new SalesInquiryManagedBean();
            //  Long salesInquiryId = Long.parseLong(request.getParameter("salesInquiryId"));
            //  salesInquiryId = smb.getSelectedViewInquiry().getId();
            ResultSet rsEvents = jasperjdbc.getConnection().prepareStatement(strSQL).executeQuery();
            JRResultSetDataSource jrResultSetDataSource = new JRResultSetDataSource(rsEvents);
            InputStream reportStream = (InputStream) getServletConfig().getServletContext().getResourceAsStream("/report/salesInquiry.jasper");
            System.out.print("Servlet");

            response.setContentType("application/pdf");
            ServletOutputStream outputStream = response.getOutputStream();
            System.out.print("REACHED SERVLET");
            HashMap parameters = new HashMap();

            JasperRunManager.runReportToPdfStream(reportStream, outputStream, new HashMap(), jrResultSetDataSource);
            System.out.print("Servlet2");
            outputStream.flush();
            outputStream.close();
        } finally {
            //      out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(salesInquiryServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JRException ex) {
            Logger.getLogger(salesInquiryServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(salesInquiryServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JRException ex) {
            Logger.getLogger(salesInquiryServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public Long getSelectedPrintInquiryID() {
        return selectedPrintInquiryID;
    }

    public void setSelectedPrintInquiryID(Long selectedPrintInquiryID) {
        this.selectedPrintInquiryID = selectedPrintInquiryID;
    }
}
